package cn.ciis.basic.kit;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.alibaba.druid.filter.config.ConfigTools;
import com.jfinal.kit.LogKit;

import java.io.*;

public class SSHKit {

    public static String DEFAULTCHART="UTF-8";

    public static Connection login(String ip,int port,String username,String password){
        boolean flag=false;
        Connection connection=null;
        try {
            connection=new Connection(ConfigTools.decrypt(ip),port);
            //连接
            connection.connect();
            //认证
            flag=connection.authenticateWithPassword(ConfigTools.decrypt(username),ConfigTools.decrypt(password));
            if (flag) {
                LogKit.info("================登录成功==================");
                return connection;
            }
        }catch (IOException e){
            LogKit.error("=========登录失败=========" + e);
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 远程执行shll脚本或者命令
     * @param connection    连接
     * @param cmd   即将执行的命令
     * @return 命令执行完后返回的结果值
     */
    public static String execmd(Connection connection,String cmd){
        String result="";
        try {
            if (connection!=null) {
                Session session=connection.openSession();//打开一次会话
                session.execCommand(cmd);//执行命令
                result=processStdout(session.getStdout(),DEFAULTCHART);
                connection.close();;
                session.close();
            }
        }catch (IOException e){
            LogKit.error("执行命令失败,执行的命令：" + cmd + "  " + e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 解析脚本执行返回的结果集
     * @param in    输入流对象
     * @param charset   编码
     * @return  以纯文本的格式返回
     */
    public static String processStdout(InputStream in,String charset){
        InputStream stdout=new StreamGobbler(in);
        StringBuffer buffer=new StringBuffer();
        try {
            BufferedReader br=new BufferedReader(new InputStreamReader(stdout,charset));
            String line=null;
            while ((line=br.readLine())!=null){
                buffer.append(line+"\n");
            }
            br.close();
        }catch (UnsupportedEncodingException e){
            LogKit.error("解析脚本出错：" + e.getMessage());
            e.printStackTrace();
        }catch (IOException e){
            LogKit.error("解析脚本出错：" + e.getMessage());
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static void main(String[] args) throws Exception {
        String ip="AerEekJS5CjGlgslT21A9SyAKrze67mcyg1ZdNBC/rNN1rBQrqObWQz6hqzuKbGHQ/Cou76opImIgwYVSiOyeA==";
        int port=2126;
        String username = "bNVOqb7WKLX5Bjnw+LMv92taj25KOxDimXxILPQjw42wgv+1lHzOH8kr97xDwWdhpY67QuYCS7sWN4W46YbkFA==";
        String password = "YJjFTs+W8K6L47nDMZE0lslC+GaOLCAK80txm3ZW7yJjTExogMa1RDH20rBFccegg/nze77VVx9WP3iQMJBP3Q==";
        String cmd = "cd /home/backup && ./backup.sh";
        //String cmd = "docker ps";//执行这样有返回的可以成功，上面备份那个 只有文件，但文件里面没内容，直接在服务器中执行那句话就有内容
        Connection connection = login(ip,port, username, password);
        String execmd = execmd(connection, cmd);
        LogKit.info("得到的结果为\n"+execmd);

    }
}
